//
//  ThemeManager.swift
//  Wanbair
//
//  Created by Li on 2025/3/6.
//

import UIKit

struct Theme: Codable {
    var name: String
    var backgroundColor: String
    var navBgColor: String
    var navTextColor: String
    var statusBarStyle: String
    var textColor: String
    var buttonColor: String
    var placeholdColor: String
    var textFieldColor: String
    var localizedTitle: [String: String]?  // 本地化标题

    // 将 statusBarStyle 字符串转换为 UIStatusBarStyle
    var statusBarStyleValue: UIStatusBarStyle {
        return statusBarStyle == "dark" ? .darkContent : .lightContent
    }
    
    // 获取当前语言的标题
    func localizedTitle(for language: String) -> String? {
        return localizedTitle?[language]
    }
    
    // 将十六进制颜色字符串转换为 UIColor
    func colorFromHex(_ hex: String) -> UIColor {
        var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        if hexString.hasPrefix("#") {
            hexString.remove(at: hexString.startIndex)
        }
        guard hexString.count == 6 else { return UIColor.gray }
        var rgbValue: UInt64 = 0
        Scanner(string: hexString).scanHexInt64(&rgbValue)
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: 1.0
        )
    }
    
}


struct ThemeContainer: Codable {
    var themes: [Theme]
}

class ThemeLoader {
    static func loadThemes() -> [Theme]? {
        guard let path = Bundle.main.path(forResource: "Themes", ofType: "json") else {
            print("Failed to find Themes.json")
            return nil
        }
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path))
            let container = try JSONDecoder().decode(ThemeContainer.self, from: data)
            return container.themes
        } catch {
            print("Failed to decode Themes.json: \(error)")
            return nil
        }
    }
}


class ThemeManager {
    
    static let shared = ThemeManager()
    
    private(set) var currentTheme: Theme
    private var themes: [Theme] = []

    private init() {
        // 加载所有主题
        self.themes = ThemeLoader.loadThemes() ?? []
        // 默认加载第一个主题
        self.currentTheme = themes.first!
    }

    func applyTheme(named themeName: String) {
        if let theme = themes.first(where: { $0.name == themeName }) {
            self.currentTheme = theme
            // 发送通知，通知所有页面更新主题
            NotificationCenter.default.post(name: .themeDidChange, object: nil)
        } else {
            print("Theme \(themeName) not found")
        }
    }

    func getAllThemes() -> [Theme] {
        return themes
    }
    
}


// 定义通知名称
extension Notification.Name {
    static let themeDidChange = Notification.Name("themeDidChange")
}


